const { Article } = require("../../models");
const { Op } = require("sequelize");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");

/**
 * 查询文章列表
 * @param req
 * @returns {Promise<{count: number, pageSize: number, rows: Model[], currentPage: number}>}
 */
exports.list = async (req) => {
  // 查询所有数据
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };
    // 模糊查询
    if (query.title) {
      condition.where = {
        title: {
          [Op.like]: `%${query.title}%`,
        },
      };
    }
    // 分页查询
    const { count, rows } = await Article.findAndCountAll(condition);
    // 返回
    return { count, rows, pageSize, currentPage };
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取文章详情
 * @param id
 * @returns {Promise<*>}
 */
exports.detail = async (id) => {
  try {
    return await this.getById(id);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 添加文章
 * @param body
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.create = async (body) => {
  try {
    return await Article.create(body);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 删除文章
 * @param id
 * @returns {Promise<void>}
 */
exports.del = async (id) => {
  try {
    const article = await this.getById(id);
    await article.destroy();
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 更新文章
 * @param id
 * @param body
 * @returns {Promise<*>}
 */
exports.update = async (id, body) => {
  try {
    const article = await this.getById(id);
    return await article.update(body);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取文章
 * @param id
 * @returns {Model}
 */
exports.getById = async (id) => {
  // 获取当前文章
  const article = await Article.findByPk(id);
  if (!article) {
    throw new NotFoundError(`ID: ${id} not found`);
  }
  return article;
};
